import { Component, OnInit, Host, ViewChild } from '@angular/core';
import { AppComponent } from '../../../app.component';
import { UsersService } from './users.service';
import { TableComponent, PaginationPositionDisplayEnum } from '../../../shared/components/table/table.component';
import { Page } from '../../../shared/components/table/models/pagination.model';
import { TableRouterLink } from '../../../shared/components/table/models/tableRouterLink.model';
import { TableOptions } from '../../../shared/components/table/models/tableOptions.model';
import { StatusEnum } from '../models/user.model';
import { ColumnOptions, ColumnType } from '../../../shared/components/table/models/columnOptions.model';
import { TableButton, ButtonType } from '../../../shared/components/table/models/tableButton.model';
import swal, { SweetAlertOptions } from 'sweetalert2';
import { ToasterService } from 'angular2-toaster';

@Component({
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss'],
  providers: [UsersService]
})
export class UsersComponent implements OnInit {
  private options: TableOptions;
  public count: number;
  public users: any[];  
  public crmSynDate: string;
  public selectedUsers: string[] = [];
  public statuses: typeof StatusEnum = StatusEnum;
  public selectedStatus: StatusEnum = StatusEnum.Active;
  public paginationPosition = PaginationPositionDisplayEnum.Down;
  public columns: ColumnOptions[] = [
    new ColumnOptions('selected', 'Select', 'col-md-1', false, ColumnType.Buttons),
    new ColumnOptions('name', 'Full Name', 'col-md-3', true, ColumnType.Link),
    new ColumnOptions('email', 'Email', 'col-md-3', false, ColumnType.Label),
    new ColumnOptions('account', 'Account', 'col-md-3', false, ColumnType.Label),
    new ColumnOptions('status', 'Status', 'col-md-2', false, ColumnType.Label)
  ];
  public filter: any = { name: '' };

  @ViewChild('usersTable') usersTable: TableComponent;

  constructor(@Host() private rootComponent: AppComponent,
  private userService: UsersService,
  private toasterService: ToasterService) { }
  
  ngOnInit() {
    this.options = new TableOptions('name');
    this.options.filter = this.filter;
    this.getUsers();
    this.userService.getLastCRMSyncDate().subscribe(data => {
      this.crmSynDate = data;
    });
  }

  public getUsers(listOnly: boolean = false) {
    if (listOnly == false) {
      if (this.options.pageOptions.skip > 0) this.usersTable.pageChanged(new Page(0, 20));
      this.userService.getUsersCount(this.options.filter.name, this.selectedStatus).subscribe(data => {
        this.count = data;
      });
    }

    this.userService.getUsersList(this.options.filter.name, this.selectedStatus, this.options.pageOptions.skip, this.options.pageOptions.take).subscribe(data => {
      this.users = data.map(user => {
        return {
          selected: [new TableButton('selected', { id: user.id, selected: this.selectedUsers.indexOf(user.id) > -1 }, true, ButtonType.CheckBox)],
          name: new TableRouterLink(user.fullName, true, [user.id]),
          email: user.email,
          account: user.account,          
          status: user.status
        }
      });
      this.rootComponent.finishLoading();
    });
  }

  public tableOptionsChanged(tableOptions: TableOptions) {
    this.options = tableOptions;
    this.getUsers(tableOptions.pageOptions.listOnly);
  }

  public onUserSelectionChanged(event: any) {
    if (event.selected == false)
        this.selectedUsers.push(event.id);
    else
        this.selectedUsers.splice(this.selectedUsers.indexOf(event.id), 1);
  }

  public resetPass() {
    const swalOptions: SweetAlertOptions = {
        buttonsStyling: false,
        customClass: 'modal-content',
        showCancelButton: true,
        title: 'Reset Password',
        text: 'The password will be reset for ' + this.selectedUsers.length + ' user(s). Are you sure that you want to continue?',
        confirmButtonClass: 'btn btn-primary',
        confirmButtonText: 'Reset',
        cancelButtonClass: 'btn btn btn-outline-dark-grey'
    };
    swal(swalOptions).then(result => {
        if (result && result.value)
            this.userService.resetPass(this.selectedUsers).subscribe(_ => {
                this.toasterService.pop('success', 'Success', 'Password(s) reset successfull.');
            });
    });
}
}
